package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.dto.UserLoginDto;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.zzyl.nursing.service.WechatService;
import com.zzyl.nursing.vo.LoginVo;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 老人家属Service业务层处理
 * 
 * @author cisimu
 * @date 2025-10-22
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService
{
    @Autowired
    private FamilyMemberMapper familyMemberMapper;

    @Autowired
    private WechatService wechatService;
    @Autowired
    private TokenService tokenService;

    private static final List<String> namePrefix = Arrays.asList("钱途无量",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝");

    /**
     * 查询老人家属
     * 
     * @param id 老人家属主键
     * @return 老人家属
     */
    @Override
    public FamilyMember selectFamilyMemberById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询老人家属列表
     * 
     * @param familyMember 老人家属
     * @return 老人家属
     */
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember)
    {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }

    /**
     * 新增老人家属
     * 
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int insertFamilyMember(FamilyMember familyMember)
    {
        return save(familyMember) ? 1 : 0;
    }

    /**
     * 修改老人家属
     * 
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int updateFamilyMember(FamilyMember familyMember)
    {
        return updateById(familyMember) ? 1 : 0;
    }

    /**
     * 批量删除老人家属
     * 
     * @param ids 需要删除的老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除老人家属信息
     * 
     * @param id 老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }


    /**
     * 小程序登录
     *
     * @param dto
     * @return
     */
    @Override
    public LoginVo login(UserLoginDto dto) {
        //1.获取openid
        String openId = wechatService.getOpenId(dto.getCode());
        if (StrUtil.isBlank(openId)) {
            throw new BaseException("登录失败");
        }
        //2.根据openid查询用户
        FamilyMember familyMember = this.lambdaQuery().eq(FamilyMember::getOpenId, openId).one();
        //3.如果用户不存在，就新增用户
        if(familyMember == null){
            Collections.shuffle(namePrefix);
            String nickName = namePrefix.get(0)+RandomStringUtils.randomNumeric(4);
            familyMember = FamilyMember.builder()
                    .name(nickName)
                    .openId(openId)
                    .build();
            this.save(familyMember);
        }
        //4.如果电话号不存在，就获取手机号
        if (StrUtil.isBlank(familyMember.getPhone())) {
            String phoneNum = wechatService.getPhoneNum(dto.getPhoneCode());
            if (StrUtil.isNotBlank(phoneNum)) {
                //5.更新手机号到用户表
                this.lambdaUpdate()
                        .eq(FamilyMember::getId,familyMember.getId())
                        .set(FamilyMember::getPhone,phoneNum)
                        .update();
            }
        }
        //6.基于openid和昵称生成token令牌
        Map<String,Object> map = new HashMap<>();
        map.put("nickName", familyMember.getName());
        map.put("userId", familyMember.getId());
        String token = tokenService.createToken(map);
        //7.封装响应结果对象
        return LoginVo.builder()
                .token(token)
                .nickName(familyMember.getName()).build();
    }
}
